package com.cskaoyan.mall.order.mq;

import com.alibaba.fastjson.JSON;
import com.cskaoyan.mall.mq.constant.MqTopicConst;
import com.cskaoyan.mall.order.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;

/**
 * @Author Pudding
 * @Date 2024/7/17 14:49
 * 延迟消息的消费者
 */
@Component
@Slf4j
public class DelayOrderConsumer {

    @Value("${rocketmq.namesrv.addr}")
    String namesrvAddr;

    @Value("${rocketmq.producer.group}")
    String producerGroup;

    @Autowired
    OrderService orderService;

    @PostConstruct
    public void init() throws MQClientException {

        //1. 创建一个消息消费者
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer(producerGroup);

        //2. 设置注册中心
        consumer.setNamesrvAddr(namesrvAddr);

        //3. 订阅主题
        consumer.subscribe(MqTopicConst.DELAY_ORDER_TOPIC, "*");

        //4. 设置消息监听器：处理订单模块的延迟消息
        consumer.setMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) {

                try {
                    MessageExt messageExt = msgs.get(0);
                    byte[] body = messageExt.getBody();
                    String messageContent = new String(body); //因为发消息的时候使用json字符串来封装的内容
                    //所以我们接受消息之后，需要使用json工具转换回去
                    Long orderId = JSON.parseObject(messageContent, Long.class);
                    log.info("订单超时，延迟消息消费成功，订单id为：{}", orderId);

                    //考虑临界情况的订单超时自动取消的业务逻辑
                    orderService.execExpiredOrder(orderId);

                    return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
                } catch (Exception e) {
                    e.printStackTrace();
                    return ConsumeConcurrentlyStatus.RECONSUME_LATER;
                }
            }
        });
        //5. 启动
        consumer.start();
    }
}
